package com.chap7;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-03-21
 * Time: 5:55
 * To change this template use File | Settings | File Templates.
 */
public class SyncDemo {
    private static int counter = 0;
    private final static MyLock lock = new MyLock();

    public static void increment(){
        lock.lock();
        try {
            counter++;
        }finally {
            lock.unLock();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                increment();
            }
        },"t1") ;

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                increment();
            }
        },"t2") ;
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        //t1 t2都执行完，主线程才执行
        System.out.println(counter);
    }

}
